<template>
  <div>
    <van-field
      v-model="childEmail"
      name="email"
      label="邮箱"
      placeholder="邮箱"
      @input="emailChange"
      :rules="[
        { required: true, message: '请填写邮箱' },
        { pattern: emailRegx, message: '邮箱格式错误' }
      ]"
    />
    <van-field
      center
      clearable
      v-model="childCode"
      name="checkCode"
      label="邮箱验证码"
      @input="inputChange"
      :rules="[
        { required: true, message: '请填写验证码' },
        { pattern: /^\d{6}$/, message: '验证码为6位数字' }
      ]"
      placeholder="请输入邮箱验证码"
    >
      <template #button>
        <van-button
          :disabled="btnDisabled"
          size="small"
          type="primary"
          native-type="button"
          @click.stop="sendCheckCode"
        >
          {{ timeCount === 0 ? "发送验证码" : timeCount }}
        </van-button>
      </template>
    </van-field>
  </div>
</template>
<script>
export default {
  props: ["value"],
  data() {
    return {
      btnDisabled: false,
      emailRegx: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
      timeCount: 0,
      childCode: "",
      childEmail: "",
      timer: null
    };
  },
  methods: {
    emailChange(v) {
      this.$emit("input", { email: v, checkCode: this.childCode });
    },
    inputChange(v) {
      this.$emit("input", { email: this.childEmail, checkCode: v });
    },
    // 发送验证码
    sendCheckCode() {
      if (!this.childEmail) {
        return this.$toast({ message: "请填写邮箱！", type: "fail" });
      }
      if (!this.emailRegx.test(this.childEmail)) {
        return this.$toast({ message: "邮箱格式不正确！", type: "fail" });
      }
      this.$apiSendCode({ email: this.childEmail }).then(res => {
        const { status, msg } = res;

        if (status === 0) {
          this.$toast({ message: msg, type: "success" });
        }
        if (status === 0 || status === 2) {
          this.setTimer();
        }
      });
    },
    setTimer() {
      this.timeCount = 5 * 60;
      this.btnDisabled = true;
      this.startTimer();
    },
    // 倒计时
    startTimer() {
      this.timer = setTimeout(() => {
        if (this.timeCount === 0) {
          this.btnDisabled = false;
          clearTimeout(this.timer);
          return;
        }
        this.timeCount--;
        this.startTimer();
      }, 1000);
    }
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  }
};
</script>
